<template>
  <div>
    <!-- 抽屉组件 -->
    <a-modal
      width="50%"
      title="上传文件"
      :visible="uploadFileVisible"
      :footer="null"
      @cancel="closeUpload">
      <slot name="title">
        <!-- @change="file => handleFileChange(file)" -->
        <!-- :preview-file="handleFileChange" -->
        <!-- :value="dataInfo.fileList" -->
        <a-upload
          ref="import"
          name="file"
          :multiple="true"
          :before-upload="beforeUploadSite"
          @change="file => handleFileChange(file)"
          :showUploadList="false"
        >
          <!-- <a-button style="margin-bottom: 10px" :loading="currentTarget.loading" :disabled="currentTarget.btnSwitch"><a-icon type="upload" v-if="!currentTarget.loading" />上传</a-button> -->
          <a-button style="margin-bottom: 10px"><a-icon type="upload" />上传</a-button>
        </a-upload>
        <a-popconfirm title="确定清空所有文件？" @confirm="clearAll">
          <a-button style="margin-left: 10px" type="danger">全部清空</a-button>
        </a-popconfirm>
      </slot>
      <a-table :columns="fileColumns" bordered :data-source="dataInfo.fileList" :rowKey="record => record.uniqueId" :pagination="false">
        <template slot="order" slot-scope="text, record, index">
          <span>{{ index + 1 }}</span>
        </template>
        <template slot="fileName" slot-scope="text, record">
          <!-- <div>{{ record.fileName }}</div> -->
          <img class="file-icon" src="~@/assets/icons/img.png" v-if="record.fileType === 1" >
          <img class="file-icon" src="~@/assets/icons/pdf.png" v-if="record.fileType === 2" >
          <img class="file-icon" src="~@/assets/icons/word.png" v-if="record.fileType === 3" >
          <span>{{ record.fileName }}</span>
          <div>
            <a-progress :percent="record.percent" v-if="record.showProgress && !record.failProgress" />
            <a-progress :percent="100" v-if="record.failProgress" status="exception" />
          </div>
        </template>
        <template slot="operate" slot-scope="text, record">
          <a @click="clickViewFile(record)">预览</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除当前文件？" @confirm="deleteFile(record)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-modal>
    <!-- 图片预览 -->
    <a-modal
      width="50%"
      :visible="imgVisible"
      :footer="null"
      @cancel="imgVisible = false"
    >
      <div class="image">
        <img :src="itemFileUrl | dealImageUrl">
      </div>
    </a-modal>
  </div>
</template>

<script>
// import cloneDeep from 'lodash.clonedeep'
import { uploadFile } from '@/api/common'
export default {
  props: {
    currentTarget: {
      type: Object,
      default: () => {
        return {}
      }
    },
    uploadFileVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      fileColumns: [
        {
          title: '序号',
          key: 'order',
          scopedSlots: { customRender: 'order' }
        },
        {
          title: '文件名',
          key: 'fileName',
          dataIndex: 'fileName',
          scopedSlots: { customRender: 'fileName' }
        },
        {
          title: '操作',
          key: 'operate',
          scopedSlots: { customRender: 'operate' }
        }
      ],
      dataInfo: {},
      imgVisible: false,
      itemFileUrl: ''
    }
  },
  methods: {
    // 赋值
    copyData (data) {
      this.dataInfo = data
    },
    beforeUploadSite (file) {
      return false
    },
    // 修改上传
    handleFileChange ({ file }) {
      console.log(file)
      const info = {}
      // 校验格式
      const formatImg = /((gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      const formatPdf = /(pdf)$/i
      // const formatWord = /((doc|docx|wps))$/i
      const formatWord = /((msword|vnd.openxmlformats-officedocument.wordprocessingml.document|kswps))$/i
      if (formatImg.test(file.type)) {
        info.fileType = 1 // 图片格式
      } else if (formatPdf.test(file.type)) {
        info.fileType = 2 // PDF格式
      } else if (formatWord.test(file.type)) {
        info.fileType = 3 // word格式
      } else {
        this.$message.error('仅支持上传图片、word及PDF文档')
        return false
      }
      // 将上传的文件进行展示
      info.fileName = file.name
      info.showProgress = true
      info.failProgress = false
      info.percent = 99
      info.uniqueId = Math.random().toString().substr(2, 10)
      if (this.dataInfo.fileList) {
        this.dataInfo.fileList.push(info)
      } else {
        this.dataInfo.fileList = []
        this.dataInfo.fileList.push(info)
      }
      const target = this.dataInfo.fileList.find(item => item.uniqueId === info.uniqueId)
      this.$forceUpdate()
      const params = new FormData()
      params.append('file', file)
      return uploadFile(params, function (e) {
        if (e.lengthComputable) {
        var rate = e.loaded / e.total // 已上传的比例
        console.log(rate, 'rate')
      }
      }).then(res => {
        target.fileUrl = res
        target.showProgress = false
        target.percent = 100
        console.log(target)
        this.$forceUpdate()
      }).catch(() => {
        // 上传失败展示失败进度条
        target.failProgress = true
        target.fileUrl = ''
        this.$forceUpdate()
      }).finally(() => {})
    },
    // 关闭弹窗
    closeUpload () {
      this.$emit('closeUpload', this.dataInfo)
    },
    // 文件预览
    clickViewFile (record) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(record.fileUrl)) {
        this.itemFileUrl = record.fileUrl
        this.imgVisible = true
        console.log(this.itemFileUrl)
      } else {
        // 打开空白页 展示文件
        const fileUrl = this.$options.filters.dealImageUrl(record.fileUrl)
        console.log(fileUrl)
        window.open(fileUrl, '_blank')
      }
    },
    // 点击删除上传的文件
    deleteFile (row) {
      const newList = this.dataInfo.fileList.filter(item => item.uniqueId !== row.uniqueId)
      this.dataInfo.fileList = newList
      this.$forceUpdate()
    },
    // 清空全部
    clearAll () {
      this.dataInfo.fileList = []
      this.$forceUpdate()
    }
  }
}
</script>
<style scoped lang="less">
  .image {
    img {
      display: block;
      width: 80%;
      margin: 10px auto;
    }
  }
  .file-icon {
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-right: 10px;
  }
</style>
